package com.nantai.jiafang.nantaijiafang.nt5s.fragments.ViewHolder;

import android.content.Context;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

import com.nantai.jiafang.nantaijiafang.Data;
import com.nantai.jiafang.nantaijiafang.nt5s.Http.Error;
import com.nantai.jiafang.nantaijiafang.nt5s.Http.HttpClient;
import com.nantai.jiafang.nantaijiafang.nt5s.Http.ResponseHandler;
import com.nantai.jiafang.nantaijiafang.nt5s.IConstant;
import com.nantai.jiafang.nantaijiafang.nt5s.bean.Uperror_Item;
import com.nantai.jiafang.nantaijiafang.nt5s.fragments.UpErrorfragment2;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.common.util.LogUtil;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;

/**
 * Created by Administrator on 2017/10/27.
 */

public class Holder_Fragment1 {
    public List<Uperror_Item> uperror_itemArrayList = new ArrayList<>();
    private Context context;
    public Holder_Fragment1( Context context2) {
        this.context = context2;
    }
    public interface Download{
        void onsuccess(ArrayList<String> paths);
       // void onfail(String error);
    }
    public interface Modifyload{
        void onsuccess();
        // void onfail(String error);
    }
    public interface Getdata {
        void data(ArrayList<Uperror_Item> uperror_items);
    }
    public void init(Getdata getdata) {
        Map<String, String> params = new HashMap<>();
        params.put("UserName", Data.NT5S_Account);
        params.put("LoginName", Data.NTLogin_Account);
        params.put("opType", "getCom");
        HttpClient client = new HttpClient(context);
        Call call = client.service(IConstant.UPERROR).getdata(params);
        Log.e(TAG, "init: " + call.request().url());
        client.request(call, new ResponseHandler() {
            @Override
            public void onSuccess(Object o) {
                ArrayList<Uperror_Item> uperror_items = (ArrayList<Uperror_Item>) o;
                getdata.data(uperror_items);
            }

            @Override
            public void onFailure(int code, Error e) {
                // Log.e("66666", "onFailure: "+e.getMessage() );
                if (e.getCode().equals("CODE_USER_ERROR")) {
                    Toast.makeText(context, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void add(String proDesc,ArrayList<String> pathlist) {
        Map<String,RequestBody> params2 = new HashMap<>();
        //以下参数是伪代码，参数需要换成自己服务器支持的
        params2.put("opType", convertToRequestBody("complaintsPlatfrom"));
        params2.put("UserName", convertToRequestBody(Data.NT5S_Account));
        params2.put("ProDesc", convertToRequestBody(proDesc));
       // params.put("count",convertToRequestBody("count"));

        List<File> fileList = new ArrayList<>();
        for (String path :
                pathlist) {
            fileList.add(new File(path));
        }
        List<MultipartBody.Part> partList = filesToMultipartBodyParts(fileList);
        HttpClient client = new HttpClient(context);
        Call<ResponseBody> call = client.service(IConstant.UPERROR).updata(params2, partList);
        Log.e(TAG, "add: "+call.request().url());
        client.request(call,new ResponseHandler(){
            @Override
            public void onSuccess(Object o) {
                Toast.makeText(context, "上传成功!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int code, Error e) {
                // Log.e("66666", "onFailure: "+e.getMessage() );
                if (e.getCode().equals("CODE_USER_ERROR")) {
                    Toast.makeText(context, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });


 /*       RequestParams params = new RequestParams("http://58.214.250.250:5055/AppHandler_Test.ashx");
        params.addBodyParameter("opType", "complaintsPlatfrom");
        params.addBodyParameter("UserName", Data.NT5S_Account);
        Log.e(TAG, "add: "+Data.NT5S_Account );
        params.addBodyParameter("ProDesc", proDesc);
        if (pathlist != null && !pathlist.isEmpty()) {
            List<KeyValue> list = new ArrayList<>();
            for (int i = 0; i < pathlist.size(); i++) {
                list.add(new KeyValue("image" + i, new File(pathlist.get(i))));
                org.xutils.http.body.MultipartBody body = new MultipartBody(list, "UTF-8");
                params.setRequestBody(body);
            }
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                updata.onsuccess(result);
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                updata.onfail(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });*/
    }
    public void modifyy(String proDesc,ArrayList<String> pathlist,Modifyload modifyload) {
        Map<String,RequestBody> params2 = new HashMap<>();
        //以下参数是伪代码，参数需要换成自己服务器支持的
        params2.put("opType", convertToRequestBody("alertCom"));
        params2.put("UserName", convertToRequestBody(Data.NT5S_Account));
        params2.put("ProDesc", convertToRequestBody(proDesc));
         params2.put("Guid",convertToRequestBody(Data.uperror_item.getGuid()));
        params2.put("Inner_No",convertToRequestBody(Data.uperror_item.getInner_No()));

        List<File> fileList = new ArrayList<>();
        for (String path :
                pathlist) {
            fileList.add(new File(path));
        }
        List<MultipartBody.Part> partList = filesToMultipartBodyParts(fileList);
        HttpClient client = new HttpClient(context);
        Call<ResponseBody> call = client.service(IConstant.UPERROR).modifyy(params2, partList);
        Log.e(TAG, "add: "+call.request().url());
        client.request(call,new ResponseHandler(){
            @Override
            public void onSuccess(Object o) {
                Toast.makeText(context, "修改成功!", Toast.LENGTH_SHORT).show();
                UpErrorfragment2.uperror_itemArrayList.get(Data.MODE).setProDesc(proDesc);
                modifyload.onsuccess();
            }

            @Override
            public void onFailure(int code, Error e) {
                // Log.e("66666", "onFailure: "+e.getMessage() );
                if (e.getCode().equals("CODE_USER_ERROR")) {
                    Toast.makeText(context, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    public void solve(String guid,String cause,String analyese,String solve,String isok) {
        Map<String,RequestBody> params2 = new HashMap<>();
        //以下参数是伪代码，参数需要换成自己服务器支持的
        params2.put("opType", convertToRequestBody("solveCom"));
        params2.put("UserName", convertToRequestBody(Data.NT5S_Account));
        params2.put("Guid", convertToRequestBody(guid));
         params2.put("Cause",convertToRequestBody(cause));
        params2.put("Analysis", convertToRequestBody(analyese));
        params2.put("Solve",convertToRequestBody(solve));
        params2.put("ISOK",convertToRequestBody(isok));
        HttpClient client = new HttpClient(context);
        Call<ResponseBody> call = client.service(IConstant.UPERROR).solve(params2);
        Log.e(TAG, "add: "+call.request().url());
        client.request(call,new ResponseHandler(){
            @Override
            public void onSuccess(Object o) {
                Toast.makeText(context, "提交成功!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(int code, Error e) {
                 Log.e("66666", "onFailure: "+e.getMessage() );
                if (e.getCode().equals("CODE_USER_ERROR")) {
                    Toast.makeText(context, e.getMessage().toString(), Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(context, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });


 /*       RequestParams params = new RequestParams("http://58.214.250.250:5055/AppHandler_Test.ashx");
        params.addBodyParameter("opType", "complaintsPlatfrom");
        params.addBodyParameter("UserName", Data.NT5S_Account);
        Log.e(TAG, "add: "+Data.NT5S_Account );
        params.addBodyParameter("ProDesc", proDesc);
        if (pathlist != null && !pathlist.isEmpty()) {
            List<KeyValue> list = new ArrayList<>();
            for (int i = 0; i < pathlist.size(); i++) {
                list.add(new KeyValue("image" + i, new File(pathlist.get(i))));
                org.xutils.http.body.MultipartBody body = new MultipartBody(list, "UTF-8");
                params.setRequestBody(body);
            }
        }
        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                updata.onsuccess(result);
            }
            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                updata.onfail(ex.getMessage());
            }

            @Override
            public void onCancelled(CancelledException cex) {
            }

            @Override
            public void onFinished() {
            }
        });*/
    }
    private  List<MultipartBody.Part> filesToMultipartBodyParts(List<File> files) {
        List<MultipartBody.Part> parts = new ArrayList<>(files.size());
        for (File file : files) {
            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
            MultipartBody.Part part = MultipartBody.Part.createFormData("multipartFiles", file.getName(), requestBody);
            parts.add(part);
        }
        return parts;
    }
    private  RequestBody convertToRequestBody(String param){
        RequestBody requestBody = RequestBody.create(MediaType.parse("text/plain"), param);
        return requestBody;
    }

    //修改
    public void getimg(String guid,Download download){
// 请求参数
        String url="http://58.214.250.250:5055/AppHandler_Test.ashx?opType=getComPic&Guid=";
        RequestParams params = new RequestParams(url+guid);
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onCancelled(CancelledException arg0) {

            }
            @Override
            public void onError(Throwable arg0, boolean arg1) {

            }
            @Override
            public void onFinished() {

            }
            @Override
            public void onSuccess(String arg0) {
                // 成功下载，显示到txtv上面
                ArrayList<String> urls=new ArrayList<>();
                try {
                    JSONArray js=new JSONArray(arg0);
                    for (int i = 0; i <js.length() ; i++) {
                        JSONObject jsonObject=js.getJSONObject(i);
                        String url= IConstant.URL_IMG+jsonObject.optString("ImagePath");
                        urls.add(url);
                    }
                        showsaveimg(urls,download);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }
    int i;
    private void showsaveimg(ArrayList<String> urls,Download download){
        ArrayList<String> filespath=new ArrayList<>();

        for ( i= 0; i <urls.size(); i++) {
                int n=i;
                long time = System.currentTimeMillis();//获取系统时间的10位的时间戳
                String str = String.valueOf(time);
                String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ str + String.valueOf(n) + ".jpg";
                String path = urls.get(n).replace(" ","%20");
                    RequestParams entity = new RequestParams(path);
                    entity.setSaveFilePath(filePath);
                    entity.setAutoResume(true);
                    x.http().get(entity, new Callback.CommonCallback<File>() {
                        @Override
                        public void onSuccess(File result) {
                            filespath.add(result.getAbsolutePath());
                            LogUtil.e("onSuccess：" + result.getAbsolutePath());
                            //Toast.makeText(context, "onSuccess：" + result.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                           // result.delete();

                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            LogUtil.e("onError "+ex.getMessage());
                            Toast.makeText(x.app(), "onError "+ex.getMessage().toString(), Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onCancelled(CancelledException cex) {
                            LogUtil.e("onCancelled ");
                        }

                        @Override
                        public void onFinished() {
                            LogUtil.e("onFinished ");
                            //Toast.makeText(x.app(), "下载成功,保存到：" + filespath.get(filespath.size() - 1), Toast.LENGTH_SHORT).show();
                            if (filespath.size()==urls.size()){
                                download.onsuccess(filespath);
                            }
                        }
                    });

        }

    }
}
